package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;

@Service
public class AlipayServiceImpl implements AlipayService {
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private RabbitService rabbitService;

    @Override
    public String submitAlipay(Long orderId) {
        try {
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
            //保存交易订单
            paymentService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());
            if ("CLOSED".equals(orderInfo.getOrderStatus()) || "PAID".equals(orderInfo.getOrderStatus())) {
                return "订单支付或已关闭";
            }
            //	官方给的代码： AlipayClient 放入spring 容器中！
            //	支付请求对象
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            //	异步回调地址
            request.setNotifyUrl(AlipayConfig.notify_payment_url);
            //	同步回调地址
            request.setReturnUrl(AlipayConfig.return_payment_url);
            //	封装业务参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
            bizContent.put("total_amount", 0.01);
            bizContent.put("subject", orderInfo.getTradeBody());
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //计算
            Calendar calendar =null;
            Calendar calendar1 = Calendar.getInstance();
            calendar1.add(Calendar.MINUTE, 10);
            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(orderInfo.getExpireTime());
            if (calendar1.compareTo(calendar2)<=0) {
                calendar = calendar1;
            } else  {
                calendar = calendar2;
            }
            bizContent.put("time_expire", simpleDateFormat.format(calendar.getTime()));



            request.setBizContent(bizContent.toString());
            String form = alipayClient.pageExecute(request).getBody();
            return form;
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public boolean refund(Long orderId) {
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        if (orderInfo != null) {
            if ("CLOSED".equals(orderInfo.getOrderStatus())) {
                return false;
            }
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
            bizContent.put("refund_amount", 0.01);
//            bizContent.put("out_request_no", "HZ01RF001");


            request.setBizContent(bizContent.toString());
            AlipayTradeRefundResponse response = null;
            try {
                response = alipayClient.execute(request);
            } catch (AlipayApiException e) {
                throw new RuntimeException(e);
            }
            if (response.isSuccess()) {
                if ("Y".equals(response.getFundChange())) {
                    PaymentInfo paymentInfo = new PaymentInfo();
                    paymentInfo.setTradeNo(response.getTradeNo());
                    paymentInfo.setPaymentStatus(PaymentStatus.CLOSED.name());
                    paymentService.updatePaymentInfoStatus(orderInfo.getOutTradeNo(), PaymentType.ALIPAY.name(), paymentInfo);
                    //异步更新订单消息
                    rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER_CANCEL, MqConst.ROUTING_ORDER_CANCEL, orderId);
                    return true;
                }

            } else {
                System.out.println("调用失败");
                return false;
            }
        }
        return false;
    }

    @Override
    public Boolean closePay(Long orderId) {
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        if (orderInfo == null) {
            return false;
        }
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if (response.isSuccess()) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean checkPayment(Long orderId) {
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        if (orderInfo == null) {
            return false;
        }
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderInfo.getOutTradeNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if (response.isSuccess()) {
            return true;
        } else {
            return false;
        }

    }

}
